package cz.khfotbal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cz.khfotbal.dao.SeasonCompetionDao;
import cz.khfotbal.domain.SeasonCompetion;

@Repository("seasonCompetionDaoImpl")
@Transactional
public class SeasonCompetionDaoImpl implements SeasonCompetionDao {

	@Autowired
	private SessionFactory sessionFactory;

	private Session session;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public List<SeasonCompetion> findAllSeasonComptionsBySeasonId(int seasonId) {
		session = sessionFactory.getCurrentSession();
		List<SeasonCompetion> result = session.createQuery(
				"from SeasonCompetion sc where sc.season.id=" + seasonId)
				.list();
		return result;
	}

	public void saveSeasonCompetion(SeasonCompetion seasonCompetion) {
		session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(seasonCompetion);
	}

	public void deleteSeasonCompetion(SeasonCompetion seasonCompetion) {
		session = sessionFactory.getCurrentSession();
		session.delete(seasonCompetion);
	}

	public SeasonCompetion findSeasonCopetionBySeasonIdAndCometionId(
			int seasonId, int competionId) {
		session = sessionFactory.getCurrentSession();
		Query query = session
				.createQuery("from SeasonCompetion sc where sc.season.id="
						+ seasonId + " and sc.competion.id=" + competionId);
		query.setCacheable(true);
		SeasonCompetion result = (SeasonCompetion) query.uniqueResult();
		return result;
	}

	public SeasonCompetion getById(int id) {
		session = sessionFactory.getCurrentSession();
		return (SeasonCompetion) session.createQuery(
				"from SeasonCompetion sc where sc.id=" + id).uniqueResult();
	}

}
